package com.bawei.mall.product.service.impl;

import com.bawei.api.RemoteMallUserService;
import com.bawei.common.core.domain.R;
import com.bawei.mall.product.domain.Dto.OrderDot;
import com.bawei.mall.product.domain.Index.ProductIndex;
import com.bawei.mall.product.domain.Po.*;
import com.bawei.mall.product.domain.Vo.CarVo;
import com.bawei.mall.product.domain.Vo.OrderListVo;
import com.bawei.mall.product.domain.Vo.OrderVo;
import com.bawei.mall.product.mapper.*;
import com.bawei.mall.product.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：liurui
 * @Package：com.bawei.mall.product.service.impl
 * @Project：mall_cloud
 * @name：IOrderServiceImpl
 */
@Service
public class COrderServiceImpl implements IOrderService {
    @Autowired
    private CCarMapper cCarMapper;
    @Autowired
    private CCarMapper mapper;

    @Autowired
    private COrderMapper cOrderMapper;

    @Autowired
    private CReadHistoryMapper cReadHistoryMapper;

    @Autowired
    private CProductMapper cProductMapper;

    @Autowired
    private CAddressMapper cAddressMapper;

    @Autowired
    private RemoteMallUserService remoteMallUserService;

    @Override
    public OrderVo generateConfirmOrder(Integer[] cartIds) {
        return getorderVo(cartIds);
    }

    @Override
    public List<OrderListVo> list(Integer status) {
        ArrayList<OrderListVo> arrayList = getarrayList(status);
        return arrayList;
    }

    @Override
    public void generateOrder(OrderDot orderDot) {
        getOrderInfo(orderDot);
        //清空购物车中下单过的id
        cCarMapper.deleteId(orderDot.getCartIds());
    }


    private OrderVo getorderVo(Integer[] cartIds) {
        OrderVo orderVo = new OrderVo();
        //给carVo赋值
        orderVo.setCartPromotionItemList(getlist(cartIds));
        //给calcAmount赋值
        orderVo.setCalcAmount(getCalcAmount(cartIds));
        //给couponHistoryDetailList赋值
        orderVo.setCouponHistoryDetailList(new ArrayList<>());
        //给integrationConsumeSetting赋值
        orderVo.setIntegrationConsumeSetting(cProductMapper.findByIntegrationConsumeSetting());
        //给memberIntegration赋值
        orderVo.setMemberIntegration(ProductIndex.SETMEMBERINTEGRATION);
        //查询登录人地址
        R<com.bawei.mall.search.domain.Po.User> r = remoteMallUserService.findUser();
        com.bawei.mall.search.domain.Po.User user = r.getData();
        List<Address> addresses = cAddressMapper.findByAddress(user.getId());
        orderVo.setMemberReceiveAddressList(addresses);
        return orderVo;
    }

    private CalcAmount getCalcAmount(Integer[] cartIds) {
        List<Car> list = mapper.findlist(cartIds);
        if (list == null || list.isEmpty()) {
            // 处理空列表的情况
            return null; // 或者返回一个带有错误信息的 CalcAmount 对象
        }
        //获取用户信息，远程调用通过redis->get(username)获取
        R<com.bawei.mall.search.domain.Po.User> r = remoteMallUserService.findUser();
        com.bawei.mall.search.domain.Po.User user = r.getData();

        //设置默认值
        BigDecimal price = BigDecimal.ZERO;
        BigDecimal promotionAmount = BigDecimal.ZERO;
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : list) {
            SkuStockList skuStock = cReadHistoryMapper.findByCar(car.getProductSkuId());
            if (skuStock != null) {
                price = price.add(BigDecimal.valueOf(skuStock.getPrice()));
            }
        }


        // 设置会员优惠金额 0黄金会员500 1铂金会员300 2钻石会员200
        Integer memberLevelId = user.getMemberLevelId();
        if(memberLevelId==0){
            //0黄金会员80%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.8)));
        }else if(memberLevelId==1){
            //1铂金会员90%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.9)));
        }else if(memberLevelId==2){
            //2钻石会员95%
            promotionAmount = price.subtract(price.multiply(BigDecimal.valueOf(0.95)));
        }

        //改造成会员优惠方式,本段属于原有操作，暂时搁置
//        if (price.compareTo(BigDecimal.valueOf(1000)) >= 0 && price.compareTo(BigDecimal.valueOf(5000)) < 0) {
//            promotionAmount = BigDecimal.valueOf(100.0);
//        } else if (price.compareTo(BigDecimal.valueOf(5000)) >= 0) {
//            promotionAmount = BigDecimal.valueOf(200.0);
//        }

        BigDecimal payAmount = price.subtract(promotionAmount);
        payAmount = payAmount.max(BigDecimal.valueOf(ProductIndex.SETFREIGHTAMOUNT)); // 确保支付金额不小于运费

        CalcAmount calcAmount = new CalcAmount();
        calcAmount.setFreightAmount(BigDecimal.valueOf(ProductIndex.SETFREIGHTAMOUNT)); // 假设运费是固定的
        calcAmount.setTotalAmount(price);
        calcAmount.setPayAmount(payAmount);
        calcAmount.setPromotionAmount(promotionAmount);
        return calcAmount;
    }

    private List<CarVo> getlist(Integer[] cartIds) {
        //查询商品信息
        //先查询相关联的表数据
        //先查询出购物车表的数据
        List<Car> list=cCarMapper.findlist(cartIds);
        ArrayList<CarVo> listVo = new ArrayList<>();
        //循环list集合Po转Vo->前台
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : list) {
            //先查询相关联的表数据
            //查询product商品表的关联数据
            Product product=cProductMapper.findByCar(car.getProductId());
            //查询sku表的关联数据
            SkuStockList skuStock=cReadHistoryMapper.findByCar(car.getProductSkuId());
            //new一个carVo对象用于赋值
            CarVo carVo = new CarVo();
            //主键id
            carVo.setId(car.getId());
            //用户id
            carVo.setMemberId(car.getMemberId());
            //用户名称
            carVo.setMemberNickname(car.getMemberNickname());
            //商品表主键id
            carVo.setProductId(car.getProductId());
            //价格
            carVo.setPrice(skuStock.getPrice());
            //品牌名称
            carVo.setProductBrand(product.getBrandName());
            //商品sn码
            carVo.setProductSn(product.getProductSn());
            //商品图片
            carVo.setProductPic(product.getPic());
            //类型编号id
            carVo.setProductCategoryId(product.getProductCategoryId());
            //sku表主键id
            carVo.setProductSkuId(skuStock.getId());
            //skucode码
            carVo.setProductSkuCode(skuStock.getSkuCode());
            //商品名称
            carVo.setProductName(product.getName());
            //商品标题
            carVo.setProductSubTitle(product.getSubTitle());
            //sku
            carVo.setProductAttr(skuStock.getSpData());
            //删除状态字段
            carVo.setDeleteStatus(car.getDeleteStatus());
            //添加时间
            carVo.setCreateDate(car.getCreateDate());
            //购物车商品数量
            carVo.setQuantity(car.getQuantity());
            //给新的集合赋值
            listVo.add(carVo);
        }
        return listVo;
    }

    private ArrayList<OrderListVo> getarrayList(Integer status) {
        //用于传送前台所需要渲染的数据
        ArrayList<OrderListVo> arrayList = new ArrayList<>();
        //用于赋值转换Vo数据
        OrderListVo orderListVo = new OrderListVo();
        //查询所有order表数据
        List<OrderInfo> infoList = cOrderMapper.findAllInfo();
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (OrderInfo orderInfo : infoList) {
            //查询所有中间表数据
            OrderInfoItem infoItemList = cOrderMapper.findAllInfoItem(orderInfo.getId());
            //查询sku表数据
            SkuStockList skuStockList=cReadHistoryMapper.findByCar(infoItemList.getSkuId());
            //查询produc表数据
            Product product = cProductMapper.findByCar(Integer.valueOf(skuStockList.getProductId()));
            //查询购物车
            //查询地址表
            Address address=cAddressMapper.findaddress(orderInfo.getAddressId());

             //TODO 部分魔法值，待效果渲染成功后，更为活值
            orderListVo.setId(orderInfo.getId());
            orderListVo.setOrderSn(product.getProductSn());
            orderListVo.setMemberId(1);
            orderListVo.setMemberUsername("member");
            //赋值
            ArrayList<OrderItem> orderItemArrayList = new ArrayList<>();

            OrderItem orderItem = new OrderItem();
            orderItem.setId(product.getId());
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCouponAmount(0);
            orderItem.setGiftGrowth(0);
            orderItem.setGiftIntegration(0);
            orderItem.setIntegrationAmount(0);
            orderItem.setOrderSn(product.getProductSn());
            orderItem.setProductAttr(skuStockList.getSpData());
            orderItem.setProductBrand(product.getBrandName());
            orderItem.setProductCategoryId(product.getProductCategoryId());
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductPic(product.getPic());
            orderItem.setProductPrice(BigDecimal.valueOf(product.getPrice()));
            orderItem.setProductQuantity(1);
            orderItem.setProductSkuCode(skuStockList.getSkuCode());
            orderItem.setProductSkuId(skuStockList.getId());
            orderItem.setProductSn(product.getProductSn());
            orderItem.setPromotionAmount(0);
            orderItem.setPromotionName("无优惠");
            orderItem.setRealAmount(BigDecimal.valueOf(5999));

            orderItemArrayList.add(orderItem);

            orderListVo.setOrderItemList(orderItemArrayList);
            orderListVo.setPayType(orderInfo.getPaymentMethod());
            orderListVo.setPayAmount(orderInfo.getActualPayment());
            orderListVo.setTotalAmount(orderInfo.getTotalAmount());
            orderListVo.setCouponAmount(BigDecimal.valueOf(100));
            orderListVo.setDiscountAmount(orderInfo.getCouponDiscount());
            orderListVo.setPromotionAmount(orderInfo.getMemberDiscount());
            orderListVo.setPromotionInfo("无优惠;满减优惠：满2000.00元，减200.00元");
            orderListVo.setFreightAmount(orderInfo.getMemberDiscount());
            orderListVo.setIntegrationAmount(BigDecimal.valueOf(0));
            orderListVo.setIntegration(0);
            orderListVo.setGrowth(0);
            orderListVo.setDeleteStatus(0);
            orderListVo.setConfirmStatus(0);
            orderListVo.setAutoConfirmDay(15);
            orderListVo.setReceiverName(address.getName());
            orderListVo.setReceiverPhone(address.getPhoneNumber());
            orderListVo.setReceiverProvince(address.getProvince());
            orderListVo.setReceiverCity(address.getCity());
            orderListVo.setReceiverRegion(address.getRegion());
            orderListVo.setReceiverDetailAddress(address.getDetailAddress());
            orderListVo.setReceiverPostCode(address.getPostCode());
            orderListVo.setSourceType(1);
            orderListVo.setOrderType(0);
            orderListVo.setStatus(3);
            orderListVo.setCreateTime(infoItemList.getCreatedAt());

            //赋值
            arrayList.add(orderListVo);
        }
        return arrayList;
    }

    private void getOrderInfo(OrderDot orderDot) {
        //订单表
        OrderInfo orderInfo = new OrderInfo();
        //订单中间表
        OrderInfoItem orderInfoItem = new OrderInfoItem();
        //根据cartIds购物车主键查询购物车数据
        List<Car> carList = cCarMapper.findlist(orderDot.getCartIds());
        //TODO 测试数据，后续可迭代为MyBatis动态查询
        for (Car car : carList) {
            Product product = cProductMapper.findByCar(car.getProductId());
            SkuStockList skuStockList = cReadHistoryMapper.findByCar(car.getProductSkuId());
            //查询地址
            Address address=cAddressMapper.findCarAddress(orderDot.getMemberReceiveAddressId());

            //TODO 部分魔法值，待效果渲染成功后，更为活值
            //用户ID，外键，关联用户表
            orderInfo.setUserId(car.getMemberId());
            //地址ID，外键，关联地址表
            orderInfo.setAddressId(address.getId());
            //订单状态默认0 未支付
            orderInfo.setOrderStatus(0);
            //支付状态
            orderInfo.setPaymentStatus(0);
            //支付方式
            orderInfo.setPaymentMethod(0);
            //实付款金额
            orderInfo.setActualPayment(BigDecimal.valueOf(product.getPrice()));
            //会员优惠金额
            orderInfo.setMemberDiscount(BigDecimal.valueOf(0.0));
            //优惠券优惠金额
            orderInfo.setCouponDiscount(BigDecimal.valueOf(0.0));
            //积分抵扣金额
            orderInfo.setPointDiscount(BigDecimal.valueOf(0.0));
            //订单总金额（不含优惠和抵扣）
            orderInfo.setTotalAmount(BigDecimal.valueOf(0.0));
            //备注信息默认无
            orderInfo.setRemark("无");
            //添加orderInfo
            cOrderMapper.addOrderInfo(orderInfo);

            //OrderInfoItem中间表
            //订单ID，外键，关联order_info表
            orderInfoItem.setOrderId(orderInfo.getId());
            //商品SKU ID，外键，关联商品SKU表
            orderInfoItem.setSkuId(skuStockList.getId());
            //商品数量
            orderInfoItem.setQuantity(1);
            //商品价格
            orderInfoItem.setPrice(BigDecimal.valueOf(skuStockList.getPrice()));
            //商品标题
            orderInfoItem.setTitle(product.getSubTitle());
            //商品缩略图URL
            orderInfoItem.setThumbnail(product.getPic());
            //添加orderInfoItem
            cOrderMapper.addOrderInfoItem(orderInfoItem);
        }
    }
}
